﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class BinaryLightAnimation : MonoBehaviour
{
    [Header("灯对象设置")]
    [Tooltip("按从高位到低位顺序排列的灯（例如：灯3灯2灯1灯0）")]
    [SerializeField] private GameObject[] lights = new GameObject[4]; // 存储四个灯对象的数组

    [Header("动画参数")]
    [Tooltip("每个数字显示持续时间（秒）")]
    [SerializeField] private float interval = 1f;

    [Tooltip("是否自动开始动画")]
    [SerializeField] private bool autoStart = true;

    private Coroutine animationCoroutine; // 协程引用

    public UnityEvent finishEvent;

    void Start()
    {
        ValidateLights();
        if (autoStart)
        {
            StartAnimation();
        }
    }

    void OnValidate()
    {
        ValidateLights();
    }

    // 验证灯设置
    void ValidateLights()
    {
        if (lights == null || lights.Length != 4)
        {
            Debug.LogError("需要准确设置4个灯对象！", this);
        }
    }

    // 开始动画
    public void StartAnimation()
    {
        if (animationCoroutine == null)
        {
            animationCoroutine = StartCoroutine(BinaryCountRoutine());
        }
    }

    // 停止动画
    public void StopAnimation()
    {
        if (animationCoroutine != null)
        {
            StopCoroutine(animationCoroutine);
            animationCoroutine = null;
            for (int i = 0; i < lights.Length; i++)
            {
                lights[i].GetComponent<Animator>().enabled = false;
            }
        }
    }

    // 核心动画协程
    IEnumerator BinaryCountRoutine()
    {
        
            for (int number = 0; number < 16; number++)
            {
                UpdateLights(number);
                yield return new WaitForSeconds(interval);
              
            }
          StopAnimation();
        finishEvent.Invoke();
        
    }

    // 更新灯状态
    void UpdateLights(int number)
    {
        // 方法1：使用位运算
        for (int i = 0; i < 4; i++)
        {
            bool isOn = (number & (1 << (3 - i))) != 0; // 高位在前
            SetLightState(i, isOn);
        }

        // 方法2：使用二进制字符串（备用方案）
        // string binary = Convert.ToString(number, 2).PadLeft(4, '0');
        // for (int i = 0; i < 4; i++)
        // {
        //     SetLightState(i, binary[i] == '1');
        // }
    }

    // 设置单个灯状态
    void SetLightState(int index, bool isOn)
    {
        if (lights != null && index < lights.Length && lights[index] != null)
        {
            lights[index].SetActive(isOn);
            lights[index].GetComponent<Animator>().enabled = isOn;
        }
    }

    void OnDisable()
    {
        StopAnimation();
    }
}
